import { Injectable } from '@nestjs/common';
import { UserWechatEntity } from './user-wechat.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class UserWechatService {
  constructor(
    @InjectRepository(UserWechatEntity)
    private readonly userWechatRepo: Repository<UserWechatEntity>
  ) {}

	async generateNickname(): Promise<string> {
		const randomNum = Math.floor(Math.random() * 10000);
		const randomString = Math.random().toString(36).substring(2, 8);
		return `用户${randomNum}${randomString}`;
	}

  async getUserWechatById(id: number): Promise<UserWechatEntity> {
    return this.userWechatRepo.findOneBy({ id });
  }

  async getUserByOpenId(openid: string): Promise<UserWechatEntity> {
    return this.userWechatRepo.findOneBy({ openid });
  }

  async createUserByOpenId(openid: string): Promise<UserWechatEntity> {
		const nikename = await this.generateNickname();

    return this.userWechatRepo.save({
      openid,
			avatar: "http://www.hicc.info:6002/fdfs/group1/M00/00/38/rBQACWfygjGAPkdPAAAr393KWRY648.png", // 初始化头像
			nickname: nikename, // 初始化昵称
			status: 1,
    });
  }

  async updateUserById(id: number, data: Partial<UserWechatEntity>): Promise<void> {
    await this.userWechatRepo.update(id, data);
  }
}
